package com.letao.server.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.letao.server.dto.UserInfoDTO;
import com.letao.server.utils.UserHolderUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.letao.server.constants.RedisConstants.LOGIN_USER_KEY;
import static com.letao.server.constants.RedisConstants.LOGIN_USER_TTL;

/**
 * 用户登录保持时间刷新拦截器
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response,
                             @NonNull Object handler) {
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        // 获取请求头中的token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            HttpSession session = request.getSession();
            token = (String) session.getAttribute("authorization");
            if (token == null)
                return true;
        }
        // 基于TOKEN获取redis中的用户
        String key = LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        // 判断用户是否存在
        if (userMap.isEmpty()) {
            return true;
        }
        // 将查询到的数据转为UserDTO
        UserInfoDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserInfoDTO(), false);
        // 存在，保存用户信息到 ThreadLocal
        UserHolderUtils.saveUser(userDTO);
        // 刷新token有效期
        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.DAYS);
        // 放行
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request,
                                @NonNull HttpServletResponse response,
                                @NonNull Object handler, Exception ex) {
        // 移除用户
        UserHolderUtils.removeUser();
    }
}
